import { Message, Notification } from 'element-ui'
import { baseURL, environment } from 'config/env.js'
import router from 'router/index.js'
import store from 'store/index.js'
import routerModule from 'router/routerModule/index.js'

import { MessageBox } from 'element-ui'

export const errimgurl = 'this.src="' + require('@/assets/img2/feng_shibaiimg.jpg') + '"'

const errType = [
  {
    value: '201',
    label: '', //"参数错误",
  },
  {
    value: '202',
    label: '', //"修改失败,请重试",
  },
  {
    value: '203',
    label: '', //"暂无数据",
  },
  {
    value: '204',
    label: '登录过期,请重新登录',
  },
  {
    value: '205',
    label: '登录过期,请重新登录', //"授权已过期,请重新登录",
  },
  {
    value: '206',
    label: '暂无权限使用该模块',
  },
  {
    value: '207',
    label: '', //"验证失败",
  },
  {
    value: '302',
    label: 'token已失效,请重新登录',
  },
  {
    value: '301',
    label: '登录过期,请重新登录',
  },
]
let flag = true
// 异常处理
function errorHandler(err) {
  console.log(err, 1221)
  if (typeof err.message === 'string') {
    let msg = err.message.split('/')
    let errInfo = errType.filter((item) => item.value - 0 === msg[0] - 0)
    if (errInfo.length) {
      if (errInfo[0].value - 0 === 205 || errInfo[0].value - 0 === 204 || errInfo[0].value - 0 === 302) {
        if (flag) {
          flag = false
          return this.$confirm('登录已过期，请重新登录', '提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            closeOnClickModal: false,
            closeOnPressEscape: false,
            showClose: false,
            type: 'error',
          }).then(() => {
            router.push({ name: 'Login', params: { action: 'refresh' } })
          })
        }
      } else if (errInfo[0].value - 0 === 301) {
        MessageBox({
          title: '提示',
          message: msg[1],
          type: 'warning',
          showClose: false,
          showCancelButton: false,
          showConfirmButton: false,
          closeOnClickModal: false,
        }).then(() => {
          window.opener = null
          window.open('about:blank', '_self')
          window.close()
        })
      } else {
        if (errInfo[0].value - 0 !== 203) {
          //暂无数据 不提示
          Message({
            type: 'warning',
            showClose: true,
            message: errInfo[0].label || msg[1],
          })
        }
      }
    } else {
      if (err.message?.indexOf('timeout') != -1) {
        msg[1] = '请求超时，请重试！'
      }
      Notification.error({
        title: '错误',
        message: msg[1] || '系统维护中',
      })
    }
  } else {
    Notification.error({
      title: '错误',
      message: '系统维护中',
    })
  }
}
//判断开始时间
function timeStartsize(startTime1, startTime2, text, text2) {
  // let reg = new RegExp('-', 'g')
  // new Date(startTime1)
  let status = true
  startTime1 = Date.parse(startTime1)
  startTime2 = Date.parse(startTime2)
  if (!startTime1 || !startTime2) {
    status = false
  }
  if (!startTime1 && !startTime2) {
    status = true
  }
  if (startTime1 == startTime2) {
    status = true
  }
  if (startTime1 < startTime2) {
    status = true
  }
  if (startTime1 > startTime2) {
    Message({
      type: 'warning',
      showClose: true,
      message: `${text ? text : ''}开始时间不能大于${text2 ? text2 : ''}开始时间`,
    })
    status = false
  }
  return status
}
//判断结束时间
function timeEndsize(endtTime1, endtTime2, text, text2) {
  // let reg = new RegExp('-', 'g')
  // new Date(startTime1)

  let status = true
  endtTime1 = Date.parse(endtTime1)
  endtTime2 = Date.parse(endtTime2)
  console.log(endtTime1 == endtTime2)
  if (!endtTime1 || !endtTime2) {
    status = false
  }
  if (!endtTime1 && !endtTime2) {
    status = true
  }
  if (endtTime1 == endtTime2) {
    status = true
  }
  if (endtTime1 >= endtTime2) {
    status = true
  }
  if (endtTime1 < endtTime2) {
    Message({
      type: 'warning',
      showClose: true,
      message: `${text ? text : ''}结束时间不能大于${text2 ? text2 : ''}结束时间`,
    })
    status = false
  }
  return status
}
function timeSlotValidator(startTime, endTime, text) {
  startTime = Date.parse(startTime)
  endTime = Date.parse(endTime)
  let status = true
  if (!endTime || !startTime) {
    status = false
  }
  if (!endTime && !startTime) {
    status = true
  }
  if (startTime > endTime) {
    Message({
      type: 'warning',
      showClose: true,
      message: `${text ? text : ''}开始时间不能大于${text ? text : ''}结束时间`,
    })
    status = false
  }
  return status
}
// 路由跳转
function pageTurn(path, query = {}, action) {
  // console.log(path)
  if (action) {
    query = Object.assign(query, { action: 'refresh' })
  }
  router.push({
    path,
    query,
  })
}
function pageTurnParams(name, params = {}) {
  router.push({
    name,
    params,
  })
}
// 设置页面tab栏
function setPageTabs() {
  let currentRoute = router.history.current
  if (currentRoute?.meta.breadcrumb) {
    let title = currentRoute?.meta.breadcrumb.split('/')
    title = title[title.length - 1]
    store.commit('pageTabState/setCurrentPageTitle', title)
    store.commit('pageTabState/setPageTabs', {
      title,
      path: currentRoute.fullPath,
    })
    let pageTabs = store.state.pageTabState.pageTabs
    //console.log(pageTabs,"pageTabs")
    pageTabs.forEach((item, i) => {
      if (item.title === title) {
        store.commit('pageTabState/setCurrentPageIndex', i)
      }
    })
  }
}
// 文件地址拼接
function fileUrl(path) {
  if (typeof path === 'string') {
    path = path.startsWith('http') ? path : `${baseURL}/uploads/${path}`
    return path
  } else {
    return ''
  }
}
// 生成路由表
function addRouterTree() {
  let routeArr = []
  let routeTree = {}
  let authorityTree = localStorage.getItem('authorityTree')
  authorityTree = JSON.parse(authorityTree)
  for (const key in routerModule) {
    let name = routerModule[key].name

    routeTree[name] = routerModule[key]
  }

  authorityTree.forEach((item) => {
    _ergodicAuthorityTree(routeTree, routeArr, item)
  })
  _addRouterTree(routeArr)
}
// 递归遍历,获取路由
function _ergodicAuthorityTree(routeTree, routeList, node, parent = {}) {
  let routerName = node.route_name
  // 处理按钮权限
  if (node.type - 0 === 2 || node.type - 0 === 3) {
    routeTree?.[parent.route_name]?.meta.btnRule.push(node.view_name)
  }
  // 处理菜单栏
  if (routerName) {
    if (node.type - 0 === 1 || node.type - 0 === 2) {
      if (routerName !== 'homePage' && routerName !== 'login') {
        // console.log(routeTree[routerName].meta.breadcrumb)
        let breadcrumb = node.path_name?.replace(/-/g, '/')
        if (routeTree[routerName]?.meta) {
          routeTree[routerName].meta.breadcrumb = breadcrumb
        }
      }
      routeTree[routerName] && routeList.push(routeTree[routerName])
    }
  }
  // 递归遍历权限树
  if (node.children && node.children.length) {
    node.children.forEach((item) => {
      _ergodicAuthorityTree(routeTree, routeList, item, node)
    })
  }
}
// 插入路由
function _addRouterTree(routeArr) {
  let arr = []
  if (environment === 'development') {
    arr = [
      /* {
        name: "activityListZiLiao",
        path: "/managementActivities/activityList/activityListZiLiao",
        component: (resolve) =>
          require([
            "views/viewport/managementActivities/activityList/ziliao/index.vue",
          ], resolve),
        meta: {
          btnRule: [],
          breadcrumb: "活动管理/活动列表/资料管理",
        },
      },
      {
        name: "tuandui",
        path: "/CompetitionManagement/megagameList/management/tuandui",
        component: (resolve) =>
          require([
            "views/viewport/CompetitionManagement/tuandui/index.vue",
          ], resolve),
        meta: {
          btnRule: [],
          breadcrumb: "大赛管理/大赛列表/团队账号设置",
        },
      }, */
      // {
      //   name: 'ShujukuList',
      //   path: '/shujuku/list',
      //   component: (resolve) => require(['views/viewport/shujuku/list/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '主题作品数据库/数据库列表',
      //   },
      // },
      // {
      //   name: 'ShujukuListAdd',
      //   path: '/shujuku/list/add',
      //   component: (resolve) => require(['views/viewport/shujuku/add/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '添加数据库',
      //   },
      // },
      // {
      //   name: 'ShujukuListChang',
      //   path: '/shujuku/list/chang',
      //   component: (resolve) => require(['views/viewport/shujuku/chang/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '编辑数据库',
      //   },
      // },
      // {
      //   name: 'Shujukuzuoping',
      //   path: '/shujuku/list/management',
      //   component: (resolve) => require(['views/viewport/shujuku/management/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '主题作品数据库/数据库列表/作品管理',
      //   },
      // },
      // {
      //   name: 'Shujukuzuopingebook',
      //   path: '/shujuku/list/management/ebook',
      //   component: (resolve) => require(['views/viewport/shujuku/management/ebook/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '主题作品数据库/数据库列表/作品管理/制作电子书',
      //   },
      // },
      // {
      //   name: 'Shujukuzuopingebookdetail',
      //   path: '/shujuku/list/management/ebookdetail',
      //   component: (resolve) => require(['views/viewport/shujuku/management/ebookDetail/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '主题作品数据库/数据库列表/作品管理/电子书详情',
      //   },
      // },
      // {
      //   name: 'Shujukuzuopingshoulu',
      //   path: '/shujuku/list/management/shoulu',
      //   component: (resolve) => require(['views/viewport/shujuku/management/shoulu/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '主题作品数据库/数据库列表/作品管理/收录优秀作品',
      //   },
      // },
      // /*  */
      // {
      //   name: 'yuedurenwu',
      //   path: '/yuedurenwu/list',
      //   component: (resolve) => require(['views/viewport/yuedurenwu/list/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '任务管理/阅读任务',
      //   },
      // },
      // {
      //   name: 'yuedurenwuadd',
      //   path: '/yuedurenwu/list/add',
      //   component: (resolve) => require(['views/viewport/yuedurenwu/add/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '阅读任务/任务管理/添加任务',
      //   },
      // },
      // {
      //   name: 'yuedurenwuchang',
      //   path: '/yuedurenwu/list/chang',
      //   component: (resolve) => require(['views/viewport/yuedurenwu/chang/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '阅读任务/任务管理/修改任务',
      //   },
      // },
      // /*  */
      // {
      //   name: 'shujutongj',
      //   path: '/shujutongj/home',
      //   component: (resolve) => require(['views/viewport/shujutongj/home/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '数据统计/数据统计',
      //   },
      // },
      // {
      //   name: 'shujutongjavatar',
      //   path: '/shujutongj/avatar',
      //   component: (resolve) => require(['views/viewport/shujutongj/avatar/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '数据统计/人物列表',
      //   },
      // },
      // {
      //   name: 'shujutongjavatardetail',
      //   path: '/shujutongj/avatar/detail',
      //   component: (resolve) => require(['views/viewport/shujutongj/avatar/detail/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '数据统计/人物列表/人物画像',
      //   },
      // },
      // /*  */
      // {
      //   name: 'zjtype',
      //   path: '/zjtype/list',
      //   component: (resolve) => require(['views/viewport/CompetitionManagement2/ttype/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '征集活动/征集类型',
      //   },
      // },
      // {
      //   name: 'zjtag',
      //   path: '/zjtag/list',
      //   component: (resolve) => require(['views/viewport/CompetitionManagement2/ttag/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '征集活动/活动标签',
      //   },
      // },
      // /*  */
      // {
      //   name: 'lockerList',
      //   path: '/locker/list',
      //   component: (resolve) => require(['views/viewport/locker/list/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '储存柜预约/预约列表',
      //   },
      // },
      // {
      //   name: 'lockeraddpavilion',
      //   path: '/locker/list/addpavilion',
      //   component: (resolve) => require(['views/viewport/locker/addpavilion/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '储存柜预约/预约列表/创建预约',
      //   },
      // },
      // {
      //   name: 'lockerchangpavilion',
      //   path: '/locker/list/changpavilion',
      //   component: (resolve) => require(['views/viewport/locker/changpavilion/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '储存柜预约/预约列表/修改预约',
      //   },
      // },
      // {
      //   name: 'lockerpersonnel',
      //   path: '/locker/list/personnel',
      //   component: (resolve) => require(['views/viewport/locker/personnel/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '储存柜预约/预约列表/预约人员',
      //   },
      // },
      // {
      //   name: 'lockerseat',
      //   path: '/locker/list/seat',
      //   component: (resolve) => require(['views/viewport/locker/seat/index.vue'], resolve),
      //   meta: {
      //     btnRule: [],
      //     breadcrumb: '储存柜预约/预约列表/储藏柜管理',
      //   },
      // },
    ]
  }
  routeArr = [...routeArr]

  routeArr.push({
    path: '*',
    redirect: '/404',
  })
  // console.log(routeArr)
  let routes = {
    path: '/',
    name: '',
    component: (resolve) => require(['views/index/index.vue'], resolve),
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        name: 'welcome',
        component: (resolve) => require(['views/viewport/welcome/index.vue'], resolve),
        meta: {
          btnRule: [],
          breadcrumb: '主页',
        },
      },
      ...routeArr,
    ],
  }
  router.addRoute(routes)
}


const commonFunc = {
  errorHandler,
  pageTurn,
  pageTurnParams,
  setPageTabs,
  fileUrl,
  addRouterTree,
  timeSlotValidator,
  timeStartsize,
  timeEndsize,
  
}

export default commonFunc
